from datetime import datetime

from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
from dateutil.relativedelta import relativedelta
from faker import Faker
from mrz.generator.td1 import TD1CodeGenerator
from pdf417 import encode, render_image

from common_utils import paste_watermark

fake = Faker(["es_AR"])


class Person:
    """
    Example found Person()

    >>>from cuil import Person
    >>>c = Person(31449202, Cuil.MALE)
    >>>c.cuil()
    20-31449202-2
    >>>c.url_dateas()
    """

    MALE = 20
    FAMALE = 27
    BUSSINES = 33
    VALID_OPTIONS = [MALE, FAMALE, BUSSINES]

    def __init__(self, dni, genre):
        self.dni = dni
        self.genre = genre

    def cuil(self):
        xy = self.genre
        z = 0
        n = 5
        adding = 0
        if self.genre in Person.VALID_OPTIONS:
            for d in str(self.genre) + str(self.dni):
                adding += int(d) * n
                n -= 1
                if n <= 1:
                    n = 7
            resto = adding - (adding / 11) * 11
            if resto > 1:
                z = 11 - resto
            elif resto == 1 and self.genre == Person.MALE:
                xy = 23
                z = 9
            elif resto == 1 and self.genre == Person.FAMALE:
                xy = 23
                z = 4
            return xy, self.dni, z
        return None


import os
import random

from .ar_utils import es_transliterate, get_ar_id_date, is_spanish


def ar_id_generate(data, result_queue):
    with Image.open("./files/ar/ar_id/bg_front.png").convert("RGBA") as bg_front:
        draw = ImageDraw.Draw(bg_front)
        font = ImageFont.truetype("fonts/Arial.ttf", 56)
        fill = 230
        space = 0
        y_correction = 5
        resizing_correction = 0

        fifteen_years = relativedelta(years=15)
        data["date_of_expiry"] = (
            datetime.strptime(data["issue_date"], "%d.%m.%Y") + fifteen_years
        ).strftime("%d.%m.%Y")
        front_fields = [
            {
                "key": "name",
                "value": data["name"],
                "pos": (905, 548 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "last_name",
                "value": data["last_name"],
                "pos": (905, 341 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "date_of_birth",
                "value": get_ar_id_date(data["date_of_birth"]),
                "pos": (913, 890 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "sex",
                "value": data["sex"],
                "pos": (905, 750 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "nationality",
                "value": "ARGENTINA",
                "pos": (1208, 750 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "issue_date",
                "value": get_ar_id_date(data["issue_date"]),
                "pos": (906, 1030 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "date_of_expiry",
                "value": get_ar_id_date(data["date_of_expiry"]),
                "pos": (906, 1178 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "dni_number",
                "value": data["dni_number"][0:2]
                + "."
                + data["dni_number"][2:5]
                + "."
                + data["dni_number"][5:],
                "pos": (178, 1345 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "dni_number_perfo",
                "value": data["dni_number"],
                "pos": (2210, 200 - y_correction),
                "angle": -90,
                "fill": 20,
            },
            {
                "key": "procedure_number",
                "value": data["procedure_number"],
                "pos": (906, 1318 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "blank_number",
                "value": data["blank_number"],
                "pos": (906, 1382 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "ejemplar",
                "value": data["ejemplar"],
                "pos": (1800, 751 - y_correction),
                "angle": 0,
                "fill": fill,
            },
        ]

        # photo
        with Image.open(f'./files/ar/ar_id/photo_usr/{data["id"]}_w.png').convert(
            "RGBA"
        ) as photo:
            photo = photo.resize((644, 818))
            photo = ImageEnhance.Brightness(photo).enhance(0.9)
            photo = ImageEnhance.Color(photo).enhance(0.7)
            layer = Image.new("RGBA", bg_front.size, (255, 255, 255, 0))
            layer.paste(photo, box=(208, 379 - y_correction), mask=photo)
            bg_front = Image.alpha_composite(bg_front, layer)
            # bg_front.paste(photo, box=(208, 379 - y_correction), mask=photo)

        # photo border
        with Image.open(f"./files/ar/ar_id/ph_bd.png").convert("RGBA") as photo:
            layer = Image.new("RGBA", bg_front.size, (255, 255, 255, 0))
            layer.paste(photo, box=(170, 358 - y_correction), mask=photo)
            bg_front = Image.alpha_composite(bg_front, layer)

            # bg_front.paste(photo, box=(170, 358 - y_correction), mask=photo)

        for field in front_fields:
            x = field["pos"][0]
            y = field["pos"][1]
            now_font = font
            if field["key"] == "dni_number":
                now_font = ImageFont.truetype("fonts/Arial Bold.ttf", 105)
            if field["key"] == "dni_number_perfo":
                now_font = ImageFont.truetype("fonts/ar_perfo.ttf", 76)
            if field["key"] == "date_of_expiry":
                now_font = ImageFont.truetype("fonts/Arial-Semibold.ttf", 56)
            now_space = space

            i = field["value"]

            line_height = sum(now_font.getmetrics())
            fontimage = Image.new(
                "L", (now_font.getbbox(i)[2] - now_font.getbbox(i)[0], line_height)
            )
            if field["key"] != "dni_number_perfo":
                ImageDraw.Draw(fontimage).text((0, 0), i, field["fill"], font=now_font)
            else:
                now_space = 5
                letters = len(i)
                x = 0
                y = 0
                layer = Image.new(
                    "L",
                    (
                        now_font.getbbox(i)[2]
                        - now_font.getbbox(i)[0]
                        + now_space * letters,
                        line_height,
                    ),
                )
                for j in i:
                    ImageDraw.Draw(layer).text((x, y), j, field["fill"], font=now_font)
                    x += (now_font.getbbox(j)[2] - now_font.getbbox(j)[0]) + now_space
                fontimage = layer

            fontimage = fontimage.rotate(
                field["angle"], resample=Image.BICUBIC, expand=True
            )
            fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
            fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
            fontimage = fontimage.filter(
                ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
            )
            fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))

            if field["key"] == "dni_number_perfo":
                w, h = fontimage.size
                fontimage = fontimage.resize((w + 20, h))

            bg_front.paste(
                (0, 0, 0), box=(int(field["pos"][0]), field["pos"][1]), mask=fontimage
            )

        # QR code
        if data["sex"] == "M":
            sex = Person.MALE
        if data["sex"] == "F":
            sex = Person.FAMALE
        c = Person(data["dni_number"], sex)
        data["end_of_qrcode"] = str(c.cuil()[0]) + str(c.cuil()[2])

        formated_date_of_birth = (
            datetime.strptime(data["date_of_birth"], "%d.%m.%Y")
        ).strftime("%d/%m/%Y")
        formated_issue_date = (
            datetime.strptime(data["issue_date"], "%d.%m.%Y")
        ).strftime("%d/%m/%Y")
        text = (
            data["procedure_number"]
            + "@"
            + es_transliterate(data["last_name"])
            + "@"
            + es_transliterate(data["name"])
            + "@"
            + data["sex"]
            + "@"
            + data["dni_number"]
            + "@"
            + data["ejemplar"]
            + "@"
            + formated_date_of_birth
            + "@"
            + formated_issue_date
            + "@"
            + data["end_of_qrcode"]
        )
        codes = encode(text, columns=3, security_level=3)
        qrcode = render_image(codes).convert("RGBA")
        qrcode = qrcode.resize((831 + 40, 193 + 40))
        pixel_data = qrcode.load()
        # Изменит альфа-канал каждого пикселя на указанный процент его исходной прозрачности
        for y in range(qrcode.size[1]):
            for x in range(qrcode.size[0]):
                if (pixel_data[x, y][0], pixel_data[x, y][1], pixel_data[x, y][2]) == (
                    255,
                    255,
                    255,
                ):
                    pixel_data[x, y] = (
                        pixel_data[x, y][0],
                        pixel_data[x, y][1],
                        pixel_data[x, y][2],
                        0,
                    )
        bg_front.paste(qrcode, box=(1412, 1200), mask=qrcode)

        # Генерация и рендер подписи
        sign = data["sign"].capitalize()
        if is_spanish(sign):
            sign = es_transliterate(sign)
        if data["signature"] != 0:
            fonts_dict = {
                1: ImageFont.truetype("./fonts/1.ttf", size=270),
                2: ImageFont.truetype("./fonts/2.ttf", size=190),
                3: ImageFont.truetype("./fonts/3.ttf", size=200),
                4: ImageFont.truetype("./fonts/4.ttf", size=100),
                5: ImageFont.truetype("./fonts/5.ttf", size=150),
                6: ImageFont.truetype("./fonts/6.ttf", size=80),
                7: ImageFont.truetype("./fonts/66.ttf", size=80),
            }
            font = fonts_dict[data["signature"]]
            width = font.getbbox(sign)[2] - font.getbbox(sign)[0]
            height = font.getbbox(sign)[3] - font.getbbox(sign)[1]
            txt = Image.new(
                "RGBA",
                (width + (width // 5), height + (height // 5)),
                (255, 255, 255, 0),
            )
            draw = ImageDraw.Draw(txt)
            draw.text(
                xy=(width // 10, height // 10),
                text=sign,
                font=font,
                fill=(0, 0, 0, 230),
                stroke_width=0,
                anchor="lt",
            )
            txt = txt.resize((300, 150))
            layer = Image.new("RGBA", bg_front.size, (255, 255, 255, 0))
            layer.paste(txt, box=(1850, 890), mask=txt)
            bg_front = Image.alpha_composite(bg_front, layer)
            # bg_front.paste(txt, box=(1850, 890), mask=txt)
            if data["signature"] == 6:
                font66 = fonts_dict[7]
                width66 = font66.getbbox("k")[2] - font66.getbbox("k")[0]
                height66 = font66.getbbox("k")[3] - font66.getbbox("k")[1]
                txt = Image.new(
                    "RGBA",
                    (width66 + (width66 // 5), height66 + (height66 // 5)),
                    (255, 255, 255, 0),
                )
                draw = ImageDraw.Draw(txt)
                draw.text(
                    xy=(width66 // 10, height66 // 10),
                    text="k",
                    font=fonts_dict[7],
                    fill=(0, 0, 0, 230),
                    anchor="lt",
                )
                txt = txt.resize((300, 30))
                layer = Image.new("RGBA", bg_front.size, (255, 255, 255, 0))
                layer.paste(
                    txt, box=(1850 + width // 4, 890 + height - (height // 6)), mask=txt
                )
                bg_front = Image.alpha_composite(bg_front, layer)
                # bg_front.paste(txt, box=(1850 + width // 4, 890 + height - (height // 6)), mask=txt)

        # Holo and photo overlay
        if data["holo"] != 0:
            with Image.open(f'./files/ar/ar_id/holo_{data["holo"]}.png').convert(
                "RGBA"
            ) as holo:
                pixel_data = holo.load()
                for y in range(holo.size[1]):
                    for x in range(holo.size[0]):
                        r, g, b, alpha = (
                            pixel_data[x, y][0],
                            pixel_data[x, y][1],
                            pixel_data[x, y][2],
                            pixel_data[x, y][3],
                        )
                        if data["holo"] == 1:
                            if alpha > 0 and alpha < 25:
                                pixel_data[x, y] = (r, g, b, alpha * 6)
                            elif alpha != 0:
                                pixel_data[x, y] = (r, g, b, int(alpha * 2.5))
                        if data["holo"] == 2:
                            if alpha > 0 and alpha < 40:
                                pixel_data[x, y] = (r, g, b, alpha * 6)
                            elif alpha != 0:
                                pixel_data[x, y] = (r, g, b, alpha * 2)
                        if data["holo"] == 3:
                            if alpha > 0 and alpha < 40:
                                pixel_data[x, y] = (r, g, b, alpha * 4)
                            elif alpha != 0:
                                pixel_data[x, y] = (r, g, b, int(alpha * 1.4))
                layer = Image.new("RGBA", bg_front.size, (255, 255, 255, 0))
                layer.paste(holo, box=(0, 0), mask=holo)
                bg_front = Image.alpha_composite(bg_front, layer)
                # bg_front.paste(holo, box=(0, 0), mask=holo)

    with Image.open("./files/ar/ar_id/bg_back.png").convert("RGBA") as bg_back:
        draw = ImageDraw.Draw(bg_back)
        font = ImageFont.truetype("fonts/Arial.ttf", 56)
        font_mrz = ImageFont.truetype("fonts/OCRB10PitchBT.otf", 125)
        fill = 230
        space = 0
        y_correction = 5
        resizing_correction = 0

        data["type"] = "ID"
        data["code_of_state"] = "ARG"

        layer = Image.new("RGBA", bg_back.size, (255, 255, 255, 255))

        with Image.open(f'./files/ar/ar_id/photo_usr/{data["id"]}_w.png').convert(
            "RGBA"
        ) as photo_2:
            photo_2 = photo_2.resize((512, 660))
            pixel_data = photo_2.load()
            # Изменит альфа-канал каждого пикселя на указанный процент его исходной прозрачности
            transparency_percent = 100
            for y in range(photo_2.size[1]):
                for x in range(photo_2.size[0]):
                    r, g, b = (
                        pixel_data[x, y][0],
                        pixel_data[x, y][1],
                        pixel_data[x, y][2],
                    )
                    old_alpha = pixel_data[x, y][3]
                    new_alpha = int(old_alpha * transparency_percent / 100)
                    pixel_data[x, y] = (r, g, b, new_alpha)
            photo_2 = ImageEnhance.Color(photo_2).enhance(0)
            photo_2 = ImageEnhance.Contrast(photo_2).enhance(3.0)
            photo_2 = ImageEnhance.Brightness(photo_2).enhance(1.0)
            pixel_data = photo_2.load()
            for y in range(photo_2.size[1]):
                for x in range(photo_2.size[0]):
                    r, g, b, alpha = (
                        pixel_data[x, y][0],
                        pixel_data[x, y][1],
                        pixel_data[x, y][2],
                        pixel_data[x, y][3],
                    )
                    if (r, g, b) != (255, 255, 255):
                        r, g, b = int(r * 0.2), 225, 170
                    pixel_data[x, y] = (r, g, b, alpha)

            photo_2 = ImageEnhance.Contrast(photo_2).enhance(1.5)
            photo_2 = ImageEnhance.Brightness(photo_2).enhance(1.1)
            layer.paste(photo_2, box=(362, 200 - y_correction), mask=photo_2)

        layer = Image.alpha_composite(layer, bg_back)
        # layer.paste(bg_back, box=(0, 0), mask=bg_back)

        bg_back = layer

        # net
        with Image.open(f"./files/ar/ar_id/net.png").convert("RGBA") as net:
            net = net.resize((760, 825))

            pixel_data = net.load()
            # Изменит альфа-канал каждого пикселя на указанный процент его исходной прозрачности
            transparency_percent = 80
            for y in range(net.size[1]):
                for x in range(net.size[0]):
                    r, g, b = (
                        pixel_data[x, y][0],
                        pixel_data[x, y][1],
                        pixel_data[x, y][2],
                    )
                    old_alpha = pixel_data[x, y][3]
                    if (r, g, b) != (230, 230, 230):
                        new_alpha = int(old_alpha * transparency_percent / 100)
                        pixel_data[x, y] = (r, g, b, new_alpha)
                    # else:
                    #     pixel_data[x, y] = (230, 230, 230, old_alpha)
            # net = ImageEnhance.Color(net).enhance(5)
            # net = ImageEnhance.Brightness(net).enhance(0.5)
            net_layer = Image.new("RGBA", bg_back.size, (255, 255, 255, 0))
            net_layer.paste(net, box=(215, 67 - y_correction), mask=net)
            # photo_2 = ImageEnhance.Contrast(net).enhance(3.0)
            bg_back = Image.alpha_composite(bg_back, net_layer)
            # bg_back.paste(net, box=(215, 67 - y_correction), mask=net)

        auth_sex = random.choice(["male", "female"])
        if auth_sex == "male":
            prefix = random.choice(["Sr. ", "Dr. "])
            data["authority"] = (
                prefix + fake.first_name_male() + " " + fake.last_name_male()
            )
        if auth_sex == "female":
            prefix = random.choice(["Sra. ", "Srta. ", "Dra. "])
            data["authority"] = (
                prefix + fake.first_name_female() + " " + fake.last_name_female()
            )

        if data["sex"] == "M":
            sex = Person.MALE
        if data["sex"] == "F":
            sex = Person.FAMALE
        c = Person(data["dni_number"], sex)
        data["cuil"] = str(c.cuil()[0]) + "-" + c.cuil()[1] + "-" + str(c.cuil()[2])
        # data['end_of_qrcode'] = str(c.cuil()[0]) + str(c.cuil()[2])

        back_fields = [
            {
                "key": "addres",
                "value": ("DOMICILIO: " + data["addres"]).split(" "),
                "pos": (147, 123 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "place_of_birth",
                "value": ("LUGAR DE NACIMIENTO: " + data["place_of_birth"]).split(" "),
                "pos": (147, 269 - y_correction),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "authority",
                "value": data["authority"],
                "pos": (
                    1280
                    - (
                        font.getbbox(data["authority"])[2]
                        - font.getbbox(data["authority"])[0]
                    )
                    / 2,
                    749,
                ),
                "angle": 0,
                "fill": fill,
            },
            {
                "key": "cuil",
                "value": data["cuil"],
                "pos": (257, 810 - y_correction),
                "angle": 0,
                "fill": fill,
            },
        ]

        # fingerprint
        if data["fingerprint"] == "СГЕНЕРИРОВАТЬ":
            fingers = os.listdir("./files/ar/ar_id/fingerprints")
            finger = random.choice(fingers)
            with Image.open(f"./files/ar/ar_id/fingerprints/{finger}").convert(
                "RGBA"
            ) as finger:
                finger = finger.resize((443, 593))
                # photo_2 = ImageEnhance.Contrast(net).enhance(3.0)
                pixel_data = finger.load()
                for y in range(finger.size[1]):
                    for x in range(finger.size[0]):
                        r, g, b = (
                            pixel_data[x, y][0],
                            pixel_data[x, y][1],
                            pixel_data[x, y][2],
                        )
                        if r > 100 and g > 100 and b > 100:
                            pixel_data[x, y] = (
                                pixel_data[x, y][0],
                                pixel_data[x, y][1],
                                pixel_data[x, y][2],
                                0,
                            )
                bg_back.paste(finger, box=(1850, 200 - y_correction), mask=finger)

        if data["fingerprint"] == "ЗАГРУЖЕНО":
            finger = f"./files/ar/ar_id/photo_usr/{data['id']}_fingerprint.png"
            with Image.open(finger).convert("RGBA") as finger:
                finger = finger.resize((443, 593))
                # photo_2 = ImageEnhance.Contrast(net).enhance(3.0)
                pixel_data = finger.load()
                for y in range(finger.size[1]):
                    for x in range(finger.size[0]):
                        r, g, b = (
                            pixel_data[x, y][0],
                            pixel_data[x, y][1],
                            pixel_data[x, y][2],
                        )
                        if r > 100 and g > 100 and b > 100:
                            pixel_data[x, y] = (
                                pixel_data[x, y][0],
                                pixel_data[x, y][1],
                                pixel_data[x, y][2],
                                0,
                            )
                bg_back.paste(finger, box=(1850, 200 - y_correction), mask=finger)

        for field in back_fields:
            x = field["pos"][0]
            y = field["pos"][1]
            now_font = font
            now_space = space

            if field["key"] != "addres" and field["key"] != "place_of_birth":
                line_height = sum(now_font.getmetrics())
                fontimage = Image.new(
                    "L",
                    (
                        now_font.getbbox(field["value"])[2]
                        - now_font.getbbox(field["value"])[0],
                        line_height,
                    ),
                )
                ImageDraw.Draw(fontimage).text(
                    (0, 0), field["value"], field["fill"], font=now_font
                )

                fontimage = fontimage.rotate(
                    field["angle"], resample=Image.BICUBIC, expand=True
                )
                fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
                fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
                fontimage = fontimage.filter(
                    ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
                )
                fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))
                bg_back.paste((0, 0, 0), box=(int(x), int(y)), mask=fontimage)
            elif field["key"] == "addres":
                for i in field["value"]:
                    if i != field["value"][len(field["value"]) - 1]:
                        i += " "
                    if (
                        x
                        + (
                            now_font.getbbox(i)[2]
                            - now_font.getbbox(i)[0]
                            - resizing_correction
                        )
                        >= 1780
                    ):
                        x = field["pos"][0]
                        y = 191 - y_correction

                    line_height = sum(now_font.getmetrics())
                    fontimage = Image.new(
                        "L",
                        (now_font.getbbox(i)[2] - now_font.getbbox(i)[0], line_height),
                    )
                    ImageDraw.Draw(fontimage).text(
                        (0, 0), i, field["fill"], font=now_font
                    )

                    fontimage = fontimage.rotate(
                        field["angle"], resample=Image.BICUBIC, expand=True
                    )
                    fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
                    fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
                    fontimage = fontimage.filter(
                        ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
                    )
                    fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))
                    bg_back.paste((0, 0, 0), box=(int(x), int(y)), mask=fontimage)
                    x += (
                        now_font.getbbox(i)[2]
                        - now_font.getbbox(i)[0]
                        - resizing_correction
                    )
            elif field["key"] == "place_of_birth":
                for i in field["value"]:
                    if i != field["value"][len(field["value"]) - 1]:
                        i += " "
                    if (
                        x
                        + (
                            now_font.getbbox(i)[2]
                            - now_font.getbbox(i)[0]
                            - resizing_correction
                        )
                        >= 1780
                    ):
                        x = field["pos"][0]
                        y = 334 - y_correction

                    line_height = sum(now_font.getmetrics())
                    fontimage = Image.new(
                        "L",
                        (now_font.getbbox(i)[2] - now_font.getbbox(i)[0], line_height),
                    )
                    ImageDraw.Draw(fontimage).text(
                        (0, 0), i, field["fill"], font=now_font
                    )

                    fontimage = fontimage.rotate(
                        field["angle"], resample=Image.BICUBIC, expand=True
                    )
                    fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
                    fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
                    fontimage = fontimage.filter(
                        ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
                    )
                    fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))
                    bg_back.paste((0, 0, 0), box=(int(x), int(y)), mask=fontimage)
                    x += (
                        now_font.getbbox(i)[2]
                        - now_font.getbbox(i)[0]
                        - resizing_correction
                    )

        # Authotity signature
        authority_sign = random.randint(1, 6)
        while authority_sign == data["signature"]:
            authority_sign = random.randint(1, 6)
        sign = data["authority"].split(" ")[-1]
        authority_sign = 6
        if len(sign) > 5:
            sign = sign.capitalize()[: random.randint(3, 5)]
        if is_spanish(sign):
            sign = es_transliterate(sign)
        if data["signature"] != 0:
            fonts_dict = {
                1: ImageFont.truetype("./fonts/1.ttf", size=270),
                2: ImageFont.truetype("./fonts/2.otf", size=190),
                3: ImageFont.truetype("./fonts/3.ttf", size=200),
                4: ImageFont.truetype("./fonts/4.ttf", size=100),
                5: ImageFont.truetype("./fonts/5.ttf", size=150),
                6: ImageFont.truetype("./fonts/6.ttf", size=80),
                7: ImageFont.truetype("./fonts/66.ttf", size=80),
            }
            font = fonts_dict[authority_sign]
            width = font.getbbox(sign)[2] - font.getbbox(sign)[0]
            height = font.getbbox(sign)[3] - font.getbbox(sign)[1]
            txt = Image.new(
                "RGBA",
                (width + (width // 5), height + (height // 5)),
                (255, 255, 255, 0),
            )
            draw = ImageDraw.Draw(txt)
            draw.text(
                xy=(width // 10, height // 10),
                text=sign,
                font=font,
                fill=(0, 0, 0, 230),
                stroke_width=0,
                anchor="lt",
            )
            txt = txt.resize((300, 150))
            layer = Image.new("RGBA", bg_back.size, (255, 255, 255, 0))
            layer.paste(
                txt,
                box=(
                    (1284 - (font.getbbox(sign)[2] - font.getbbox(sign)[0]) // 2, 600)
                ),
                mask=txt,
            )
            bg_back = Image.alpha_composite(bg_back, layer)
            # bg_back.paste(txt, box=((1284 - (font.getbbox(sign)[2] - font.getbbox(sign)[0]) // 2, 600)), mask=txt)
            if authority_sign == 6:
                font66 = fonts_dict[7]
                width66 = font66.getbbox("k")[2] - font66.getbbox("k")[0]
                height66 = font66.getbbox("k")[3] - font66.getbbox("k")[1]
                txt = Image.new(
                    "RGBA",
                    (width66 + (width66 // 5), height66 + (height66 // 5)),
                    (255, 255, 255, 0),
                )
                draw = ImageDraw.Draw(txt)
                draw.text(
                    xy=(width66 // 10, height66 // 10),
                    text="k",
                    font=fonts_dict[7],
                    fill=(0, 0, 0, 200),
                    anchor="lt",
                )
                txt = txt.resize((300, 30))
                layer = Image.new("RGBA", bg_back.size, (255, 255, 255, 0))
                layer.paste(
                    txt,
                    box=(1284 - width66 // 2, 600 + height - (height // 6)),
                    mask=txt,
                )
                bg_back = Image.alpha_composite(bg_back, layer)
                # bg_back.paste(txt, box=(1284 - width66 // 2, 600 + height - (height // 6)), mask=txt)

        name = es_transliterate(data["name"])
        last_name = es_transliterate(data["last_name"])

        mrz_code = TD1CodeGenerator(
            data["type"],
            data["code_of_state"],
            data["dni_number"],
            data["date_of_birth"][8:]
            + data["date_of_birth"][3:5]
            + data["date_of_birth"][0:2],
            data["sex"],
            data["date_of_expiry"][8:]
            + data["date_of_expiry"][3:5]
            + data["date_of_expiry"][0:2],
            data["code_of_state"],
            last_name,
            name,
        )
        mrz_strs = str(mrz_code).split("\n")

        fontimage = Image.new(
            "L",
            (
                font_mrz.getbbox(mrz_strs[0])[2] - font_mrz.getbbox(mrz_strs[0])[0],
                sum(font_mrz.getmetrics()),
            ),
        )
        ImageDraw.Draw(fontimage).text((0, 0), mrz_strs[0], fill=200, font=font_mrz)
        fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
        fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
        fontimage = fontimage.filter(
            ImageFilter.UnsharpMask(radius=1, percent=400, threshold=5)
        )
        fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))
        bg_back.paste((0, 0, 0), box=(70, 1098), mask=fontimage)

        fontimage = Image.new(
            "L",
            (
                font_mrz.getbbox(mrz_strs[1])[2] - font_mrz.getbbox(mrz_strs[1])[0],
                sum(font_mrz.getmetrics()),
            ),
        )
        ImageDraw.Draw(fontimage).text((0, 0), mrz_strs[1], fill=200, font=font_mrz)
        fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
        fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
        fontimage = fontimage.filter(
            ImageFilter.UnsharpMask(radius=1, percent=400, threshold=5)
        )
        fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))
        bg_back.paste((0, 0, 0), box=(70, 1220), mask=fontimage)

        fontimage = Image.new(
            "L",
            (
                font_mrz.getbbox(mrz_strs[2])[2] - font_mrz.getbbox(mrz_strs[2])[0],
                sum(font_mrz.getmetrics()),
            ),
        )
        ImageDraw.Draw(fontimage).text((0, 0), mrz_strs[2], fill=200, font=font_mrz)
        fontimage = fontimage.filter(ImageFilter.MaxFilter(1))
        fontimage = fontimage.filter(ImageFilter.EDGE_ENHANCE)
        fontimage = fontimage.filter(
            ImageFilter.UnsharpMask(radius=1, percent=400, threshold=5)
        )
        fontimage = fontimage.filter(ImageFilter.GaussianBlur(1.0))
        bg_back.paste((0, 0, 0), box=(70, 1333), mask=fontimage)

        bg_front = bg_front.resize((1012, 638))
        bg_back = bg_back.resize((1012, 638))
        image_name = f'./files/ar/ar_id/photo_usr/{data["id"]}_completed'
        if data["size"] == "DOC":
            bg = Image.new("RGBA", (1012 * 2 + 10, 638), (255, 255, 255, 255))
            bg.paste(bg_front, box=(0, 0), mask=bg_front)
            bg.paste(bg_back, box=((1012 + 10), 0), mask=bg_back)
            bg.paste(bg_back, box=((1012 + 10), 0), mask=bg_back)
            pixel_data = bg.load()
            for y in range(bg.size[1]):
                for x in range(bg.size[0]):
                    if x < 50 or (x > 962 and x < 1072) or x > 1984:
                        r, g, b, alpha = (
                            pixel_data[x, y][0],
                            pixel_data[x, y][1],
                            pixel_data[x, y][2],
                            pixel_data[x, y][3],
                        )
                        if (r, g, b) == (255, 255, 255):
                            pixel_data[x, y] = (r, g, b, 0)
            bg.save(image_name + ".png")
            result_queue.put(image_name)
        elif data["size"] == "A4":
            bg = Image.new("RGB", (2481, 3507), (255, 255, 255))
            bg_front = bg_front.rotate(
                random.uniform(-0.9, 0.9), resample=Image.BICUBIC, expand=True
            )
            bg_back = bg_back.rotate(
                random.uniform(-0.9, 0.9), resample=Image.BICUBIC, expand=True
            )
            bg.paste(bg_front, box=(120, 120), mask=bg_front)
            bg.paste(bg_back, box=((1020 + 30 + 110), 120), mask=bg_back)
            bg.save(image_name + ".png")
            result_queue.put(image_name)

    image_path = f'./files/ar/ar_id/photo_usr/{data["id"]}_completed.png'
    path_to_save = f'./files/ar/ar_id/photo_usr/{data["id"]}_wm.png'
    paste_watermark(image_path, path_to_save)


exemplary_data = {
    "name": "CERIZOLA LUCERO",
    "last_name": "ÑSCET",
    "date_of_birth": "19.01.2005",
    "sex": "M",
    "issue_date": "23.03.2020",
    "dni_number": "46260175",
    "procedure_number": "00631475345",
    "blank_number": "7522",
    "ejemplar": "A",
    "addres": "SJDHFBSJD KFDBSKDF KDFKSDFJHSD KJDFSKHJSDFH KFDSHJ",
    "place_of_birth": "ARGENTINA",
    "signature": 6,
    "sign": "ÑSCET",
    "holo": 3,
    "fingerprint": "СГЕНЕРИРОВАТЬ",
    "size": "DOC",
    "id": "276802147",
}

# ar_id_generate(exemplary_data, queue.Queue())
"""
if __name__ == "__main__":
    try:
        kz_id_old_generate(exemplary_data, queue.Queue())
    except:
        print("Ошибка")
        id_old
"""
